import React from "react";
import { Resend } from "resend";
import { validateString, getErrorMessage } from "@/lib/utils";
import ContactFormEmail from "@/email/contact-form-email";
import { NextRequest, NextResponse } from "next/server";

const resend = new Resend(process.env.RESEND_API_KEY);

const sendEmail_ = async (formData: any) => {
  // const senderEmail = formData.get("senderEmail");
  // const message = formData.get("message");
  const senderEmail = formData.senderEmail;
  const message = formData.message;
  console.log("sendEmail", senderEmail, message);
  // simple server-side validation
  if (!validateString(senderEmail, 500)) {
    return {
      error: "Invalid sender email",
    };
  }
  if (!validateString(message, 5000)) {
    return {
      error: "Invalid message",
    };
  }

  let data;
  try {
    data = await resend.emails.send({
      from: "onboarding@resend.dev",
      to: "295448382@qq.com",
      subject: "Message from contact form",
      reply_to: senderEmail,
      react: React.createElement(ContactFormEmail, {
        message: message,
        senderEmail: senderEmail,
      }),
    });
  } catch (error: unknown) {
    console.log("errror email", error);
    return {
      error: getErrorMessage(error),
    };
  }

  return {
    data,
  };
};

export const POST = async (req: any) => {
  if (true) {
    const formData = await req.json();
    console.log("formData", formData);
    try {
      // 调用第三方服务的 API
      const { data, error } = await sendEmail_(formData);
      console.log("data", data);
      console.log("error", error);
      // 响应结果
      return NextResponse.json({
        status: data ? "success" : "error",
        message: data ? data.id : error,
      });
    } catch (error) {
      console.error("Error:", error);
      // 处理错误响应
      return NextResponse.json({ error: error });
    }
  }
};
